package task;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;

import dao.JxDao;
import dao.TaskInfoDao;
import model.TaskInfo;
import util.UUIDGenerator;


@Configuration
@EnableScheduling // 启用定时任务
public class TaskForExpenditure {
	
	@Autowired
	TaskInfoDao taskInfoDao;
	
	@Autowired
	JxDao jxDao;
	
	//维修合同数据录入费用表 
	@Transactional
	@Scheduled(cron = "* * 0 * * ?")
    public void contractJx() {
		TaskInfo task = taskInfoDao.getTask(1001);
		//判断开关是否开启（1：开启，0：关闭）
		if(task.getStatus() == 1){
			//抓取需要重复跑批的数据（task_flag = 2）,删除绩效表中已存在数据
			List<Long> contractIdList = jxDao.queryAgainContract();
			jxDao.deleteAgainContract(contractIdList);
			
			//抓取需要跑批的数据（task_flag = 2 or task_flag = 0）
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
			List<Map<String, Object>> contractJx = jxDao.contractJx(null);
			
			//修改标识（task_flag = 1）
			List<Long> listId = new ArrayList<Long>();
			for (Map<String, Object> map : contractJx) {
				Long id = Long.parseLong(map.get("contract_id").toString());
				listId.add(id);
			}
			jxDao.updateFlagContract(listId);
			
			//跑批数据处理
			for (Map<String, Object> map : contractJx) {
				String sdate = map.get("start_date").toString();
				String edate = map.get("end_date").toString();
				// 开始年份
				Date date = null;
				try {
					date = sdf.parse(sdate);
				} catch (ParseException e) {
					e.printStackTrace();
					throw new RuntimeException();
				}
				// 计算月份，循环多少次
				Calendar a = Calendar.getInstance();
				a.setTime(date);
				int startDate = a.get(Calendar.YEAR);
				int startMonth = a.get(Calendar.MONTH) + 1;	//月份从0开始，所以补1
				int index = 0;
				try {
					index = dateUtil(sdate, edate)+1;
				} catch (ParseException e) {
					e.printStackTrace();
				}//月份补1
				Float amount = div(map.get("amount").toString(),index);
				List<Map<String, Object>> insertList = new ArrayList<Map<String,Object>>();
				for (int i = 0; i < index; i++) {
					Map<String,Object> insertMap = new HashMap<String, Object>();
					if (startMonth == 13) {
						startDate = startDate + 1;
						startMonth = 1;
					}
					insertMap.put("time_year", startDate);
					insertMap.put("time_month", startMonth);
					insertMap.put("time", startDate + "-" + startMonth + "-05");
					insertMap.put("amount", amount);
					insertMap.put("id", UUIDGenerator.getUniqueLong());
					insertMap.put("assets_id", map.get("assets_id"));
					insertMap.put("assets_name", map.get("assets_name"));
					insertMap.put("type", 1);
					insertMap.put("hospital_id", map.get("hospital_id"));
					insertMap.put("task_no",1001);
					insertMap.put("contract_id",map.get("contract_id"));
					insertList.add(insertMap);
					startMonth++;
				}
				int insertJx = jxDao.insertJx(insertList);
				System.out.println("------------------------insert num :"+insertJx);
			}
			System.out.println("------------------------insert num :");
		}
    }
	
	
	//维修派工费用录入费用表 
	@Transactional
	@Scheduled(cron = "* * 1 * * ?")
    public void dispatchJx() {
		TaskInfo task = taskInfoDao.getTask(1002);
		//判断开关是否开启（1：开启，0：关闭）
		if(task.getStatus() == 1){
			//抓取需要重复跑批的数据（task_flag = 2）,删除绩效表中已存在数据
			List<Long> dispatchIdList = jxDao.queryAgainDispatch();
			jxDao.deleteAgainDispatch(dispatchIdList);
			
			//抓取需要跑批的数据（task_flag = 2 or task_flag = 0）
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
			List<Map<String, Object>> dispatchJx = jxDao.dispatchJx();
			
			//修改标识（task_flag = 1）
			List<Long> listId = new ArrayList<Long>();
			for (Map<String, Object> map : dispatchJx) {
				Long id = Long.parseLong(map.get("id").toString());
				listId.add(id);
			}
			jxDao.updateFlagDispatch(listId);
			
			//跑批数据处理
			List<Map<String, Object>> insertList = new ArrayList<Map<String,Object>>();
			for (Map<String, Object> map : dispatchJx) {
				String sdate = map.get("create_time").toString();
				// 开始年份
				Date date = null;
				try {
					date = sdf.parse(sdate);
				} catch (ParseException e) {
					e.printStackTrace();
					throw new RuntimeException(); 
				}
				Calendar a = Calendar.getInstance();
				a.setTime(date);
				int startDate = a.get(Calendar.YEAR);
				int startMonth = a.get(Calendar.MONTH) + 1;	//月份从0开始，所以补1
					
				Map<String,Object> insertMap = new HashMap<String, Object>();
				insertMap.put("time_year", startDate);
				insertMap.put("time_month", startMonth);
				insertMap.put("time", startDate + "-" + startMonth + "-05");
				insertMap.put("amount", map.get("amount"));
				insertMap.put("id", UUIDGenerator.getUniqueLong());
				insertMap.put("assets_id", map.get("assets_id"));
				insertMap.put("assets_name", map.get("assets_name"));
				insertMap.put("type", 1);
				insertMap.put("hospital_id", map.get("hospital_id"));
				insertMap.put("task_no",1002);
				insertMap.put("contract_id",0);
				insertList.add(insertMap);
			}
			int insertJx = jxDao.insertJx(insertList);
			System.out.println("------------------------insert num :"+insertJx);
		}
    }
	
	
	//保养费用录入费用表 
	@Transactional
	@Scheduled(cron = "* * 2 * * ?")
    public void upkeepJx() {
		TaskInfo task = taskInfoDao.getTask(1003);
		//判断开关是否开启（1：开启，0：关闭）
		if(task.getStatus() == 1){
			//抓取需要重复跑批的数据（task_flag = 2）,删除绩效表中已存在数据
			List<Long> upkeepIdList = jxDao.queryAgainUpkeep();
			jxDao.deleteAgainUpkeep(upkeepIdList);
			
			//抓取需要跑批的数据（task_flag = 2 or task_flag = 0）
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
			List<Map<String, Object>> upkeepJx = jxDao.upkeepJx();
			
			//修改标识（task_flag = 1）
			List<Long> listId = new ArrayList<Long>();
			for (Map<String, Object> map : upkeepJx) {
				Long id = Long.parseLong(map.get("id").toString());
				listId.add(id);
			}
			jxDao.updateFlagUpkeep(listId);
			
			//跑批数据处理
			List<Map<String, Object>> insertList = new ArrayList<Map<String,Object>>();
			for (Map<String, Object> map : upkeepJx) {
				String sdate = map.get("create_time").toString();
				// 开始年份
				Date date = null;
				try {
					date = sdf.parse(sdate);
				} catch (ParseException e) {
					e.printStackTrace();
					throw new RuntimeException(); 
				}
				Calendar a = Calendar.getInstance();
				a.setTime(date);
				int startDate = a.get(Calendar.YEAR);
				int startMonth = a.get(Calendar.MONTH) + 1;	//月份从0开始，所以补1
					
				Map<String,Object> insertMap = new HashMap<String, Object>();
				insertMap.put("time_year", startDate);
				insertMap.put("time_month", startMonth);
				insertMap.put("time", startDate + "-" + startMonth + "-05");
				insertMap.put("amount", map.get("amount"));
				insertMap.put("id", UUIDGenerator.getUniqueLong());
				insertMap.put("assets_id", map.get("assets_id"));
				insertMap.put("assets_name", map.get("assets_name"));
				insertMap.put("type", 1);
				insertMap.put("hospital_id", map.get("hospital_id"));
				insertMap.put("task_no",1003);
				insertMap.put("contract_id",0);
				insertList.add(insertMap);
			}
			int insertJx = jxDao.insertJx(insertList);
			System.out.println("------------------------insert num :"+insertJx);
		}
    }
	
	//配件费用录入费用表 
	@Transactional
	@Scheduled(cron = "* * 3 * * ?")
    public void partJx() {
		TaskInfo task = taskInfoDao.getTask(1004);
		//判断开关是否开启（1：开启，0：关闭）
		if(task.getStatus() == 1){
			//抓取需要重复跑批的数据（task_flag = 2）,删除绩效表中已存在数据
			List<Long> partIdList = jxDao.queryAgainPart();
			jxDao.deleteAgainPart(partIdList);
			
			//抓取需要跑批的数据（task_flag = 2 or task_flag = 0）
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
			List<Map<String, Object>> upkeepJx = jxDao.upkeepJx();
			
			//修改标识（task_flag = 1）
			List<Long> listId = new ArrayList<Long>();
			for (Map<String, Object> map : upkeepJx) {
				Long id = Long.parseLong(map.get("id").toString());
				listId.add(id);
			}
			jxDao.updateFlagUpkeep(listId);
			
			//跑批数据处理
			List<Map<String, Object>> insertList = new ArrayList<Map<String,Object>>();
			for (Map<String, Object> map : upkeepJx) {
				String sdate = map.get("create_time").toString();
				// 开始年份
				Date date = null;
				try {
					date = sdf.parse(sdate);
				} catch (ParseException e) {
					e.printStackTrace();
					throw new RuntimeException(); 
				}
				Calendar a = Calendar.getInstance();
				a.setTime(date);
				int startDate = a.get(Calendar.YEAR);
				int startMonth = a.get(Calendar.MONTH) + 1;	//月份从0开始，所以补1
					
				Map<String,Object> insertMap = new HashMap<String, Object>();
				insertMap.put("time_year", startDate);
				insertMap.put("time_month", startMonth);
				insertMap.put("time", startDate + "-" + startMonth + "-05");
				insertMap.put("amount", map.get("amount"));
				insertMap.put("id", UUIDGenerator.getUniqueLong());
				insertMap.put("assets_id", map.get("assets_id"));
				insertMap.put("assets_name", map.get("assets_name"));
				insertMap.put("type", 1);
				insertMap.put("hospital_id", map.get("hospital_id"));
				insertMap.put("task_no",1004);
				insertMap.put("contract_id",0);
				insertList.add(insertMap);
			}
			int insertJx = jxDao.insertJx(insertList);
			System.out.println("------------------------insert num :"+insertJx);
		}
    }
		
	public int dateUtil(String sdate, String edate) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		Calendar bef = Calendar.getInstance();
		Calendar aft = Calendar.getInstance();
		bef.setTime(sdf.parse(sdate));
		aft.setTime(sdf.parse(edate));
		int result = aft.get(Calendar.MONTH) - bef.get(Calendar.MONTH);
		int month = (aft.get(Calendar.YEAR) - bef.get(Calendar.YEAR)) * 12;
		return Math.abs(month + result);
	}

	public Float div(String v1, int v2) {
		BigDecimal b1 = new BigDecimal(v1);
		BigDecimal b2 = new BigDecimal(Integer.toString(v2));
		return b1.divide(b2,3, BigDecimal.ROUND_HALF_UP).floatValue();
	}
	
	public static void main(String[] args) {
		List<Integer> list = new ArrayList<Integer>();
		for(int i = 0;i<10;i++){
			list.add(i);
		}
		System.out.println(list.toString());
		int limit = 3;
		int count = list.size()/limit;
		int yu = list.size() % limit;
		List<Integer> subList = new ArrayList<Integer>();
		for(int i = 0;i<count;i++){
			if(i+1 == count){
				subList = list.subList(i*count, (i+1)*count+yu);
			}else{
				subList = list.subList(i*count, (i+1)*count);
			}
			System.out.println(subList.toString());
		}
		
		
		
		
	}
}
